package com.cj.gateway.jwtutil;

import com.cj.common.response.Result;
import com.cj.gateway.service.LoginFeignService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @Author cheng jun
 * @Description:
 * @Date 2021/5/28 18:24
 */
/**
 * 支持Nacos的动态刷新功能
 */
@RefreshScope
@RestController
@RequestMapping("/gatewayUser")
public class LoginController {

    @Value("${org.my.jwt.jwt-key}")
    private String jwtKey;

    @Value("${org.my.jwt.jwt-ttl}")
    private String jwtTtl;

    @Resource
    private LoginFeignService loginFeignService;

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Map<String, Object> user) {
        Map<String, Object> result = new HashMap<>();

        Result login = loginFeignService.login(user);
        if (login.getCode() == 0) {
            String token = new JWTUtil(jwtKey, jwtTtl).createJWT(UUID.randomUUID().toString(), String.valueOf(user.get("username")), null);
            result.put("token", token);
            result.put("name", String.valueOf(user.get("username")));
        } else {
            return login;
        }
        return Result.success(result);
    }

    /**
     * 退出
     */
    @PostMapping("/sys/logout")
    public Result logout() {
        return loginFeignService.logout();
    }
}
